import {
  ScoreSubmitParamData,
  scoreBySelfTemporarySave,
  selectPmData,
  scoreByLeaderSubmit,
  AnnexData
} from '@/api/myPerformance'
import {PMContent, PMLayout, PMNav} from '@/components/others/layout'
import {CnBoldP, CnBoldSpan, CnMediumSpan, CnNormalP} from '@/components/text'
import useModal from '@/hooks/modalHook'
import {useRouteQuery} from '@/hooks/pageRedirect'
import useMyPm from '@/hooks/pm/myPm'
import useOwner from '@/hooks/pm/owner'
import useProgress from '@/hooks/pm/progress'
import {useTableLoading} from '@/hooks/tableHook'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {SelfScoreQuery} from '@/libs/pageRedirect'
import {replaceBreak, zeroize, checkValueIsInRange} from '@/libs/toolkit'
import {ddGetAuth, ddUploadFile} from '@/api/dd'
import PhoneLayout from '@/layout/index_phone'
import ScoreDimen from './components/EditDimen'
import {defineComponent, reactive, computed, onMounted} from 'vue'

const {message} = ant_design_vue
interface CustomPmTarget extends MyPm.PmTarget {
  score: number | undefined
  scoreContent: string
  scoreDesc: string
}

interface CustomPmData extends Omit<MyPm.PmData, 'pmTargetList'> {
  pmTargetList: CustomPmTarget[]
}

export default defineComponent({
  name: 'scoreBySelf',
  setup(props, ctx) {
    const {getQueryData, router} = useRouteQuery({
      queryKeys: ['defaultPmId']
    })
    const queryData = getQueryData<SelfScoreQuery>()
    if (!queryData) {
      router.back()
      return () => (
        <PMLayout>
          <PMNav></PMNav>
          <PMContent></PMContent>
        </PMLayout>
      )
    }
    const {defaultPmId} = queryData

    const {store} = useGlobalAPI()

    const {loading, startLoading, closeLoading} = useTableLoading()

    const {
      scoreSelfByLoginUser,
      loginUser,
      scoreLeaderByLoginUser,
      appointByLoginUser,
      getPmProgress,
      nowRunning,
      nowRunningByLoginuser
    } = useProgress({
      pmId: defaultPmId
    })

    const {pm, getPmByPmId, getPmDataByPmId, totalScoreBySelf} = useMyPm()

    const {owner, udpateOwner} = useOwner()

    let state = reactive<{
      /**当前绩效的维度列表 */
      pmDataList: CustomPmData[]

      /**评分总结 */
      summarize: string

      /**附件 */
      fileList: {
        uid: string // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
        name: string // 文件名
        status: 'uploading' | 'done' | 'error' | 'removed' // 状态有：uploading done error removed
      }[]
      /**已上传附件 */
      annexDataList: AnnexData[]
    }>({
      pmDataList: [],
      summarize: '',
      annexDataList: [],
      fileList: []
    })

    /**表格头 */
    // const tableColumns = computed<CColumn<CustomPmTarget>[]>(() => {
    //   let columns: CColumn<CustomPmTarget>[] = [
    //     {
    //       title: '指标名称',
    //       dataIndex: 'pmTargetName',
    //       ellipsis: true,
    //       width: 160
    //     },
    //     {
    //       title: '权重(%)',
    //       dataIndex: 'pmTargetWeight',
    //       width: 80,
    //       align: 'center',
    //       ellipsis: true
    //     },
    //     {
    //       title: '考核标准',
    //       dataIndex: 'pmTargetStand',
    //       ellipsis: true,
    //       minWidth: 120
    //     }
    //   ]

    //   // 根据自评人数，动态添加自评栏
    //   const selfCheckColumns: CColumn<CustomPmTarget>[] = allScoreSelf.value.map((item, idx) => ({
    //     title: `自评(${item.makeUserName})`,
    //     children: [
    //       {
    //         title: '评分',
    //         dataIndex: ['scoreSelfCheckList', idx + '', 'score'],
    //         align: 'center',
    //         width: 80,
    //         ellipsis: true
    //       },
    //       {
    //         title: '评分说明',
    //         dataIndex: ['scoreSelfCheckList', idx + '', 'scoreContent'],
    //         align: 'center',
    //         width: 180,
    //         ellipsis: true
    //       }
    //     ]
    //   }))
    //   columns.push(...selfCheckColumns)

    //   if (scoreLeaderByLoginUser.value) {
    //     const leaderCheckColumns: CColumn<CustomPmTarget>[] = [
    //       {
    //         title: `主管-${scoreLeaderByLoginUser.value.makeUserName}(${scoreLeaderByLoginUser.value.scoreWeight}%)`,
    //         dataIndex: 'score',
    //         align: 'center',
    //         width: 160,
    //         ellipsis: true
    //       },
    //       {
    //         title: `评分说明`,
    //         dataIndex: 'scoreContent',
    //         align: 'center',
    //         width: 180,
    //         ellipsis: true
    //       }
    //     ]

    //     columns.push(...leaderCheckColumns)
    //   } else if (appointByLoginUser.value) {
    //     const appointColumns: CColumn<CustomPmTarget>[] = [
    //       {
    //         title: `指定人员评分-${appointByLoginUser.value.makeUserName}(${appointByLoginUser.value.scoreWeight}%)`,
    //         dataIndex: 'score',
    //         align: 'center',
    //         width: 160,
    //         ellipsis: true
    //       },
    //       {
    //         title: `评分说明`,
    //         dataIndex: 'scoreContent',
    //         align: 'center',
    //         width: 180,
    //         ellipsis: true
    //       }
    //     ]

    //     columns.push(...appointColumns)
    //   }

    //   console.log('主管评分表格头', columns)

    //   return columns
    // })

    const scoreCount = computed(() => {
      let num = (eval(
        (state.pmDataList || [])
          .map(item =>
            item.pmTargetList.map(target => {
              if (target.isBonus === 0) {
                return (
                  (target.score || 0) *
                  (target.pmTargetWeight / 100) *
                  ((scoreLeaderByLoginUser.value === undefined
                    ? 100
                    : scoreLeaderByLoginUser.value.scoreWeight) /
                    100)
                )
              } else {
                return target.score || 0
              }
            })
          )
          .flat(Infinity)
          .join('+')
      ) || 0) as number

      let returnData = zeroize(num, 2, true)

      return returnData
    })

    function getTableData() {
      startLoading()
      /**获取个人绩效中的维度及指标数据 */
      getPmDataByPmId({
        pmId: Number(defaultPmId),
        updatePmData: true,
        success(data) {
          if (data && data.length === 0) {
            state.pmDataList = []
          } else {
            data.sort((a, b) => a.sort - b.sort)
            let pmDataList: CustomPmData[] = data.map<CustomPmData>(item => ({
              pmId: item.pmId,
              pmDimensionId: item.pmDimensionId,
              pmDimensionName: item.pmDimensionName,
              pmDimensionTypeCode: item.pmDimensionTypeCode,
              pmDimensionWeight: item.pmDimensionWeight,
              isCustomSelf: item.isCustomSelf,
              isImport: item.isImport,
              sort: item.sort,
              pmTargetList: item.pmTargetList
                .filter(item => {
                  /**当前登陆者不是该绩效所属人时 */
                  // 当前登陆者是主管评分人,且目标评分人有人时
                  if (scoreLeaderByLoginUser.value && item.appointUserDDId) {
                    return false
                  } else if (
                    appointByLoginUser.value &&
                    item.appointUserDDId !== appointByLoginUser.value.makeUserDDId
                  ) {
                    // 当前登陆者是目标指定评分人,且该目标的指定评分人不是当前登陆者时
                    return false
                  } else {
                    // 都不是的时候，当前登陆者就是管理员
                    return true
                  }
                })
                .map<CustomPmTarget>(target => {
                  let scoreLeader = target.leaderCheckList?.find(
                    item => item && item.makeUserDDId === loginUser.value.userId
                  )
                  return {
                    isBonus: target.isBonus,
                    pmTargetRange: target.pmTargetRange,
                    appointScoreSign: target.appointScoreSign,
                    appointUserDDId: target.appointUserDDId,
                    makeProperty: undefined,
                    pmTargetId: target.pmTargetId,
                    pmDimensionId: target.pmDimensionId,
                    pmTargetName: target.pmTargetName,
                    pmTargetStand: target.pmTargetStand,
                    pmTargetWeight: target.pmTargetWeight,
                    sort: target.sort,
                    score: scoreLeader ? scoreLeader.score : undefined,
                    scoreContent: '',
                    scoreDesc: '',
                    scoreSelfCheckList: target.scoreSelfCheckList,
                    leaderCheckList: target.leaderCheckList,
                    appointCheckList: target.appointCheckList,
                    isMustSelect: target.isMustSelect
                  }
                })
            }))

            console.log(pmDataList)
            // 给每个维度添加一个总分项
            // for (let i = 0; i < pmDataList.length; i++) {
            //   const pmData = pmDataList[i]
            //   let pmTargetList = pmData.pmTargetList

            // 根据自评人数创建新的的自评列表
            // let coustomScoreSelfCheckList: MyPm.ScoreSelfCheck[] = allScoreSelf.value.map(
            //   item => ({
            //     pmTargetCheckId: -1,
            //     makeUserDDId: item.makeUserDDId,
            //     makeUserName: item.makeUserName,
            //     pmTargetId: -1,
            //     pmProgressId: item.pmProgressId,
            //     score: 0,
            //     scoreContent: '',
            //     scoreDesc: '',
            //     scoreWeight: item.scoreWeight
            //   })
            // )

            // 给默认的自评列表填充自评人的评分
            // for (let j = 0; j < pmTargetList.length; j++) {
            //   const pmTarget = pmTargetList[j]

            //   let scoreSelfCheckList = pmTarget.scoreSelfCheckList || []

            //   for (let k = 0; k < scoreSelfCheckList.length; k++) {
            //     const scoreSelfCheck = scoreSelfCheckList[k]

            //     // coustomScoreSelfCheckList[k].score +=
            //     //   (scoreSelfCheck.score * pmTarget.pmTargetWeight) / 100
            //   }
            // }

            // 当前维度所有指标权重
            // let pmTargetWeightCount = eval(
            //   pmData.pmTargetList
            //     .map(target => target.pmTargetWeight)
            //     .flat(Infinity)
            //     .join('+')
            // ) as number

            // 将新的自评列表加入总分项中
            // pmTargetList.push({
            //   isBonus: 0,
            //   pmTargetRange: '0-100',
            //   appointScoreSign: 0,
            //   appointUserDDId: '',
            //   pmTargetId: -1,
            //   pmDimensionId: -1,
            //   pmTargetName: '总分',
            //   pmTargetStand: '',
            //   pmTargetWeight: pmTargetWeightCount,
            //   sort: 999,
            //   score: 0,
            //   scoreContent: '',
            //   scoreDesc: '',
            //   scoreSelfCheckList: coustomScoreSelfCheckList.map(item => {
            //     item.score = numRound(item.score, 1)
            //     return item
            //   }),
            //   leaderCheckList: [],
            //   appointCheckList: [],
            //   isMustSelect: 0
            // })
            // }

            state.pmDataList = pmDataList
            console.log('个人绩效中有数据', data, pmDataList)
          }
          closeLoading()
        },
        error() {
          closeLoading()
        }
      })
    }

    /**组合数据 */
    function combScoreBySelfSubmitParamData(data: CustomPmData[]): ScoreSubmitParamData[] | false {
      if (!nowRunning.value || !nowRunning.value.length) return false
      console.log(data)
      console.log(nowRunningByLoginuser.value)

      let returnData: ScoreSubmitParamData[] = []

      for (let i = 0; i < data.length; i++) {
        const dimension = data[i]

        for (let ii = 0; ii < dimension.pmTargetList.length; ii++) {
          const target = dimension.pmTargetList[ii]

          // 当score为空时，判断是否是加分项，加分项可不做输入校验
          if (target.score === undefined) {
            if (target.isBonus === 1 && nowRunningByLoginuser.value) {
              returnData.push({
                makeUserDDId: loginUser.value.userId,
                makeUserName: loginUser.value.userName,
                pmProgressId: nowRunningByLoginuser.value.pmProgressId,
                pmTargetId: target.pmTargetId,
                score: 0,
                scoreContent: target.scoreContent,
                scoreDesc: ''
              })
            } else {
              message.warning(
                `维度：${dimension.pmDimensionName}中，指标：${target.pmTargetName}的自评未输入`
              )
              return false
            }
          } else {
            // 当score不为空时，判断是否是加分项
            // 加分项不得超过输入范围

            if (target.isBonus === 1 && !checkValueIsInRange(target.score, target.pmTargetRange)) {
              message.warning(
                `维度：${dimension.pmDimensionName}中，加分项：${target.pmTargetName}的自评不在范围内。当前加分项范围为：${target.pmTargetRange}`
              )
              return false
            }

            if (nowRunningByLoginuser.value) {
              returnData.push({
                makeUserDDId: loginUser.value.userId,
                makeUserName: loginUser.value.userName,
                pmProgressId: nowRunningByLoginuser.value.pmProgressId,
                pmTargetId: target.pmTargetId,
                score: target.score || 0,
                scoreContent: target.scoreContent,
                scoreDesc: ''
              })
            }
          }
        }
      }
      return returnData
    }

    /**点击提交时 */
    function handleSubmitClick() {
      handleScoreSummarizeConfirm(state.summarize)
    }

    /**输入总结后确认 */
    function handleScoreSummarizeConfirm(data?: string) {
      let paramData = combScoreBySelfSubmitParamData(state.pmDataList)
      console.log(paramData)

      if (!paramData) return

      if (!scoreLeaderByLoginUser.value && !appointByLoginUser.value) return

      let pmProgressId = scoreLeaderByLoginUser.value
        ? scoreLeaderByLoginUser.value.pmProgressId
        : appointByLoginUser.value
        ? appointByLoginUser.value.pmProgressId
        : undefined

      if (!pmProgressId) return

      console.log(pmProgressId)

      for (let i = 0; i < state.fileList.length; i++) {
        const file = state.fileList[i]
        if (file.status !== 'done') {
          message.warning('文件未上传结束，请等待！')
          return
        }
      }

      startLoading()
      scoreByLeaderSubmit({
        pmProgressId: pmProgressId,
        data: paramData,
        scoreSummary: replaceBreak(data ? data : ''),
        annexData: state.annexDataList
      })
        .then(res => {
          closeLoading()
          router.back()
        })
        .catch(err => {
          closeLoading()
          getPageData()
        })
    }

    /**暂存 */
    function handleTemporarySaveClick() {
      if (!scoreSelfByLoginUser.value) return
      let data = combScoreBySelfSubmitParamData(state.pmDataList)
      if (!data) return
      scoreBySelfTemporarySave({
        pmProgressId: scoreSelfByLoginUser.value.pmProgressId,
        data: data
      })
        .then(res => {
          getPageData()
        })
        .catch(err => {})
    }

    /**获取页面数据 */
    function getPageData() {
      getPmByPmId({
        pmId: Number(defaultPmId),
        updatePm: true,
        success: data => {
          udpateOwner({ownerDDId: data.pmUserDDId})
        }
      })

      getPmProgress({
        pmId: defaultPmId,
        updatePmProgress: true
      })

      getTableData()
    }

    onMounted(() => {
      getPageData()
    })

    return () => (
      <PhoneLayout>
        <div class='flex-1 flex flex-col overflow-hidden'>
          {/* 用户信息 */}
          <div class='w-full h-80 bg-white flex items-center gap-x-8 px-16'>
            <img src={owner.value?.avatar} class='w-40 h-40 rounded-4'></img>
            <div>
              <CnBoldP>{owner.value?.userName || ''}</CnBoldP>
              <CnNormalP>{owner.value?.deptName || ''}</CnNormalP>
              {pm.value ? <CnNormalP>{pm.value.pmFormName || ''}</CnNormalP> : null}
            </div>
          </div>
          {/* 绩效内容 */}
          <div class='flex-1 overflow-y-auto flex flex-col gap-y-12 pb-16'>
            <div class='w-full flex flex-col gap-y-12 pb-16'>
              {state.pmDataList &&
                state.pmDataList.map((dimen, idx) =>
                  owner.value ? (
                    <ScoreDimen
                      sourceType='self'
                      hidden={false}
                      dimension={dimen}
                      pmId={Number(defaultPmId)}
                      onDimensionChange={data => {
                        console.log('维度数据变化', data)
                        state.pmDataList[idx] = data
                      }}
                      owner={owner.value}
                    ></ScoreDimen>
                  ) : null
                )}
            </div>

            <div class='px-12'>
              <div class='flex items-center gap-x-8 mb-12'>
                <CnMediumSpan class='inline-block w-60 text-right'>总分</CnMediumSpan>
                <CnBoldSpan>{scoreCount.value}</CnBoldSpan>
              </div>
              <div class='flex items-center gap-x-8 mb-12'>
                <CnMediumSpan class='inline-block w-60 text-right'>评分总结</CnMediumSpan>
                <a-textarea
                  class='flex-1'
                  v-model={[state.summarize, 'value']}
                  row={2}
                ></a-textarea>
              </div>
              <div class='flex items-center gap-x-8'>
                <CnMediumSpan class='inline-block w-60 text-right'>附件</CnMediumSpan>
                <a-upload
                  v-model={[state.fileList, 'file-list']}
                  multiple={true}
                  data={(file: File) => file}
                  customRequest={async (e: {data: File; file: {uid: string}}) => {
                    let res = await ddGetAuth({userDDId: loginUser.value.userId}).catch(err => {})
                    if (!res) return
                    let formData = new FormData()
                    formData.append('file', e.data)
                    formData.append('userDDId', loginUser.value.userId)

                    ddUploadFile(formData)
                      .then(res => {
                        let currentFileIdx = state.fileList.findIndex(
                          item => item.uid === e.file.uid
                        )
                        state.fileList[currentFileIdx].status = 'done'
                        state.annexDataList[currentFileIdx] = {
                          annexFileExtension: res.data.dentry.extension,
                          annexFileId: res.data.dentry.id,
                          annexFileName: res.data.dentry.name,
                          annexFileSize: res.data.dentry.size,
                          annexFileSpaceId: res.data.dentry.spaceId
                        }
                      })
                      .catch(err => {
                        let currentFileIdx = state.fileList.findIndex(
                          item => item.uid === e.file.uid
                        )
                        state.fileList[currentFileIdx].status = 'error'
                        let fileName = state.fileList[currentFileIdx].name
                        message.error(`文件(${fileName})上传失败,请删除后重新上传！`)
                      })
                  }}
                  onRemove={(file: {uid: string}) => {
                    let currentFileIdx = state.fileList.findIndex(item => item.uid === file.uid)
                    state.annexDataList.splice(currentFileIdx, 1)
                  }}
                >
                  <a-button>
                    <i class='iconfont icon-ziliaoshangchuan'></i>
                    上传附件
                  </a-button>
                </a-upload>
              </div>
            </div>
          </div>
          {/* 底部按钮 */}
          <div class='h-60 bg-white border-t-1 border-cardLine flex items-center justify-center z gap-x-12 px-16 overflow-x-auto'>
            <a-button type='primary' onClick={handleSubmitClick}>
              提交
            </a-button>
          </div>
        </div>
      </PhoneLayout>
    )
  }
})
